package com.mzba.place.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.mzba.place.entity.SafecardEntity;
import com.mzba.place.utils.StreamByteUtil;

/**
 * 位置信息表
 * @author 06peng
 *
 */
public class SafeCardTable {

	public String TABLE_NAME = "safecard_db";
	public static final String _id = "_id";
	public static final String MD5 = "md5";
	public static final String CONTENT = "content";
	
	private DBManagerImpl db = null;
	
	public SafeCardTable(Context context) {
		if (db == null) {
			db = DBManager.get(context);
		}
		if (!db.isTableExits(db.getConnection(), TABLE_NAME)) {
			createTable();
		}
	}
	
	public SafeCardTable() {
		
	}
	
	public void createTable() {
		String createTableSql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME
				+ "(_id integer primary key autoincrement, " + MD5 + " VARCHAR, " + CONTENT + " BLOB)";
		db.creatTable(db.getConnection(), createTableSql, TABLE_NAME);
		
	}
	
	public void save(SafecardEntity entity) {
		try {
			ContentValues value = new ContentValues();
			value.put(CONTENT, StreamByteUtil.ObjectToByte(entity));
			value.put(MD5, entity.getMd5());
			db.save(db.getConnection(), TABLE_NAME, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void update(SafecardEntity entity) {
		Cursor cursor = null;
		try {
			cursor = db.find(db.getConnection(), "select * from " + TABLE_NAME + " where "+MD5+" = ?", new String[] {entity.getMd5()});
			if (cursor != null) {
				while (cursor.moveToNext()) {
					delete(entity.getMd5());
				}
			} 
			save(entity);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != cursor) {
				cursor.close();
				cursor = null;
			}
		}
	}
	
	public List<SafecardEntity> get() {
		List<SafecardEntity> statusList = new ArrayList<SafecardEntity>();
		Cursor cursor = null;
		try {
			cursor = db.find(db.getConnection(), "select * from " + TABLE_NAME, null);
			if (cursor != null) {
				while (cursor.moveToNext()) {
					SafecardEntity entity = ((SafecardEntity) StreamByteUtil.ByteToObject(cursor.getBlob(cursor.getColumnIndex(CONTENT))));
					statusList.add(entity);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != cursor) {
				cursor.close();
				cursor = null;
			}
		}
		return statusList;
	}
	
	private void delete(String md5) {
		db.delete(db.getConnection(), TABLE_NAME, MD5 + "=?", new String[] { md5 });
	}
	
	public void clearTable() {
		db.delete(db.getConnection(), TABLE_NAME, null, null);
	}
}
